﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ComLib.Lang.AST;
using FluentScript.IDE.Lib;
using ComLib.Lang;
using ComLib.Lang.Helpers;


namespace FluentScript.IDE.Parts
{

    /// <summary>
    /// Represents the UI for showing the local variables in the script.
    /// </summary>
    public class Output : ViewPartBase
    {
        private static List<string> _prints;
        private TextBox _textBox;


        public Output(TextBox textbox)
        {
            _textBox = textbox;
            _prints = new List<string>();
        }


        /// <summary>
        /// Updates the ui.
        /// </summary>
        public override void Update()
        {
            string output = BuildResults();
            _textBox.Text = output;
        }


        /// <summary>
        /// Clears the UI.
        /// </summary>
        public override void Clear()
        {
            _prints.Clear();
            _textBox.Text = string.Empty;
        }


        /// <summary>
        /// Prints to the console.
        /// </summary>
        /// /// <param name="settings">Settings for interpreter</param>
        /// <param name="exp">The functiona call expression</param>
        /// <param name="printline">Whether to print with line or no line</param>
        public static string Print(FunctionCallExpr exp)
        {
            string message = LogHelper.BuildMessage(exp.ParamList);
            _prints.Add(message);
            return message;
        }


        private string BuildResults()
        {
            var result = Context.Ip.Result;
            var success = result.Success ? "yes" : "no";
            string results = string.Format("Success: {0}", success);

            if (!result.Success)
                results += Environment.NewLine + "Message: " + result.Message + Environment.NewLine;

            if (result.Ex != null)
                results += Environment.NewLine + result.Ex.StackTrace;
            
            string prints = BuildPrintMsgs();
            string finaloutput = results + Environment.NewLine + prints;
            return finaloutput;
        }



        /// <summary>
        /// Build up all the print messages.
        /// </summary>
        /// <returns></returns>
        private string BuildPrintMsgs()
        {
            string output = "";
            foreach (var msg in _prints)
                output += msg + Environment.NewLine;
            return output;
        }
    }
}
